//
//  MapServiceViewController.m
//  ASHT_IOS
//
//  Created by 宋安安 on 14-4-10.
//  Copyright (c) 2014年 宋安安. All rights reserved.
//

#import "MapServiceViewController.h"
#import "NearbyViewController.h"
#import "RoadMapViewController.h"
#import "AFAppDotNetAPIClient.h"
#import "AFHTTPRequestOperation.h"
#import "BMKOverlay.h"
#import "MapDetailedViewController.h"
@interface MapServiceViewController ()

@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end

@implementation UIImage(InternalMethod)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
{
    
    CGFloat width = CGImageGetWidth(self.CGImage);
    CGFloat height = CGImageGetHeight(self.CGImage);
    
	CGSize rotatedSize;
    
    rotatedSize.width = width;
    rotatedSize.height = height;
    
	UIGraphicsBeginImageContext(rotatedSize);
	CGContextRef bitmap = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
	CGContextRotateCTM(bitmap, degrees * M_PI / 180);
	CGContextRotateCTM(bitmap, M_PI);
	CGContextScaleCTM(bitmap, -1.0, 1.0);
	CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}

@end
@implementation MapServiceViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        isarler=YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _mapView = [[BMKMapView alloc]init];


    /*d电子地图定位*/
    _mapView.showMapScaleBar = true;
    _mapView.mapScaleBarPosition=CGPointMake(0, 0);
    _mapView.zoomEnabled = true;
    _mapView.zoomLevel = 16;
    BMKLocationViewDisplayParam *lvdp=[[BMKLocationViewDisplayParam alloc] init];
    lvdp.isRotateAngleValid=YES;
    lvdp.isAccuracyCircleShow=NO;
    lvdp.locationViewOffsetX=0.00f;
    lvdp.locationViewOffsetY=0.00f;
    lvdp.locationViewImgName=@"bnavi_icon_location_fixed";
    [_mapView updateLocationViewWithParam:lvdp];
    _userLocation=[[BMKUserLocation alloc] init];
    [_userLocation startUserLocationService];
    [_mapView setShowsUserLocation:YES];
    _mapView.userTrackingMode=BMKUserTrackingModeFollow;
    [self.view_Content addSubview:_mapView];
    [self.view_Content addSubview:view_select];
     dic_BMKPoiInfo=[[NSMutableDictionary alloc]init];
    _search=[[BMKSearch alloc] init];
    arr_polygon=[[NSMutableArray alloc] init];
    arr_pop=[[NSMutableArray alloc] init];
    arr_rect=[[NSMutableArray alloc] init];
    arr_popAnnotation=[[NSMutableArray alloc] init];
    text_select.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addOverlayView];
    // Do any additional setup after loading the view from its nib.
}
#pragma mark mapViewDelegate 代理方法
-(void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    region.center.latitude  = userLocation.location.coordinate.latitude;
    region.center.longitude = userLocation.location.coordinate.longitude;
    starcoor.latitude=userLocation.location.coordinate.latitude;
    starcoor.longitude=userLocation.location.coordinate.longitude;

//    _mapView.userTrackingMode=BMKUserTrackingModeFollow;

}
- (void)viewDidGetLocatingUser:(CLLocationCoordinate2D)userLoc
{
    [_mapView setRegion:region animated:YES];
    [_userLocation stopUserLocationService];
}
- (void)mapStatusDidChanged:(BMKMapView *)mapView
{
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置 nil,否则影响内存的释放
    _userLocation.delegate=self;
    _search.delegate=self;
    _mapView.frame=CGRectMake(0, 0, view_content.frame.size.width,view_content.frame.size.height);
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时,置 nil
    _userLocation.delegate=nil;
    _search.delegate=nil;
    isarler=YES;
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}
- (void)onGetAddrResult:(BMKSearch*)searcher result:(BMKAddrInfo*)result errorCode:(int)error
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
    NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
    for (BMKPointAnnotation *Annotation in array) {
        for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
            if ([Annotation isEqual:Polygon1])
            {
                [arr_Annotation removeObject:Polygon1];
            }
        }
    }
    [_mapView removeAnnotations:arr_Annotation];
    array = [NSMutableArray arrayWithArray:_mapView.overlays];
    NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
    for (BMKOverlayView *Overlay in array) {
        for (BMKPolygon *Polygon1 in arr_polygon) {
            if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
            {
                [arr_Overlay removeObject:Polygon1];
            }
        }
        
    }
    [_mapView removeOverlays:arr_Overlay];
	if (error == 0) {
		BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
		item.coordinate = result.geoPt;
		item.title = result.strAddr;
		[_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.geoPt;
	}
}
-(IBAction)btn_01_onClick:(id)sender
{
    [text_select resignFirstResponder];
    if (text_select.text.length>0)
    {
        [self selectNearby:text_select.text page:0];
        
    }
    else
    {
        NearbyViewController *neaebyVC=[[NearbyViewController alloc] initWithNibName:XIB_Version(@"NearbyViewController") bundle:nil];
        neaebyVC.nearbydelegate=self;
        [self.app.viewDeckController.navigationController pushViewController:neaebyVC animated:YES];
        neaebyVC=nil;
    }
}

-(void) textFieldDidEndEditing:(UITextField *)textField
{
    if([textField isEqual:text_select])
    {
        if ([textField.text isEqualToString:@""]) {
            NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
            NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
            for (BMKPointAnnotation *Annotation in array) {
                for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
                    if ([Annotation isEqual:Polygon1])
                    {
                        [arr_Annotation removeObject:Polygon1];
                    }
                }
            }
            [_mapView removeAnnotations:arr_Annotation];
            array = [NSMutableArray arrayWithArray:_mapView.overlays];
            NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
            for (BMKOverlayView *Overlay in array) {
                for (BMKPolygon *Polygon1 in arr_polygon) {
                    if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
                    {
                        [arr_Overlay removeObject:Polygon1];
                    }
                }
                
            }
            [_mapView removeOverlays:arr_Overlay];
        }
        
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //开始编辑时触发，文本字段将成为first responder
    if([textField isEqual:text_select])
    {
       
    }
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
    NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
    for (BMKPointAnnotation *Annotation in array) {
        for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
            if ([Annotation isEqual:Polygon1])
            {
                [arr_Annotation removeObject:Polygon1];
            }
        }
    }
    [_mapView removeAnnotations:arr_Annotation];
    array = [NSMutableArray arrayWithArray:_mapView.overlays];
    NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
    for (BMKOverlayView *Overlay in array) {
        for (BMKPolygon *Polygon1 in arr_polygon) {
            if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
            {
                [arr_Overlay removeObject:Polygon1];
            }
        }
        
    }
    [_mapView removeOverlays:arr_Overlay];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
    [self btn_01_onClick:nil];
    return YES;
}
#pragma mark  poi搜索方法
-(void)selectNearby:(NSString *)tyeName page:(int)page
{
   bool flag=[_search poiSearchNearBy:tyeName center:starcoor radius:5000 pageIndex:page];
    
    if (flag) {
       [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    else
    {
        NSLog(@"搜索失败");
    }
}
#pragma mark  poi搜索回调方法
- (void)onGetPoiResult:(BMKSearch*)searcher result:(NSArray*)poiResultList searchType:(int)type errorCode:(int)error
{
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
    NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
    for (BMKPointAnnotation *Annotation in array) {
        for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
            if ([Annotation isEqual:Polygon1])
            {
                [arr_Annotation removeObject:Polygon1];
            }
        }
    }
    [_mapView removeAnnotations:arr_Annotation];
    array = [NSMutableArray arrayWithArray:_mapView.overlays];
    NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
    for (BMKOverlayView *Overlay in array) {
        for (BMKPolygon *Polygon1 in arr_polygon) {
            if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
            {
                [arr_Overlay removeObject:Polygon1];
            }
        }
    }
    [_mapView removeOverlays:arr_Overlay];
  
    if (error == BMKErrorOk) {
        [dic_BMKPoiInfo removeAllObjects];
		BMKPoiResult* result = [poiResultList objectAtIndex:0];
		for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
           
            [dic_BMKPoiInfo setObject:poi forKey:poi.name];
            [_mapView addAnnotation:item];
            if(i == 0)
            {
                //将第一个点的坐标移到屏幕中央
                _mapView.userTrackingMode=BMKUserTrackingModeNone;
//                _mapView.centerCoordinate = poi.pt;
                [_mapView setShowsUserLocation:NO];
                BMKCoordinateRegion cr;
                cr.center.latitude  = poi.pt.latitude;
                cr.center.longitude = poi.pt.longitude;
                [_mapView setRegion:cr animated:YES];
                [_mapView setShowsUserLocation:YES];
            }
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
		}
	} else if (error == BMKErrorRouteAddr){
        NSLog(@"起始点有歧义");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } else if (error ==BMKErrorResultNotFound){
        // 各种情况的判断。。。
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示"
                                                     message:@"未找到结果"
                                                    delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        alert=nil;
    }
    else if(error==BMKErrorConnect)
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示"
                                                     message:@"网络连接错误"
                                                    delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        alert=nil;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }
    else
    {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }

}
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
	
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        for (id <BMKAnnotation>  annotat in arr_popAnnotation) {
            if ([annotation isEqual:annotat]) {
                ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorPurple;
            }else
            {
                ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
            }
        }
        
		// 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
	
    // 设置位置
	annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
//    annotationView.image=[UIImage imageNamed:@"map_select"];
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
	annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
}
//点击地图空白
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    [text_select resignFirstResponder];
    NSLog(@"onClickedMapBlank-latitude==%f,longitude==%f",coordinate.latitude,coordinate.longitude);
    int i=0;
    for (id<BMKOverlay>  overlay in arr_rect) {
        
        BMKPolygonView* polygonView = [[BMKPolygonView alloc] initWithOverlay:overlay];
        CGRect rect=[polygonView rectForMapRect:overlay.boundingMapRect];
    
        CLLocationCoordinate2D coords[4]={0};
        coords[0].latitude = coordinate.latitude;
        coords[0].longitude = coordinate.longitude;
        coords[1].latitude = coordinate.latitude;
        coords[1].longitude = coordinate.longitude;
        coords[2].latitude = coordinate.latitude;
        coords[2].longitude = coordinate.longitude;
        coords[3].latitude = coordinate.latitude;
        coords[3].longitude = coordinate.longitude;
        BMKPolygon *polygon1 = [BMKPolygon polygonWithCoordinates:coords count:4];
        id<BMKOverlay> overlay1=polygon1;
        BMKPolygonView* polygonView1 = [[BMKPolygonView alloc] initWithOverlay:overlay1];
        CGRect rect1=[polygonView1 rectForMapRect:overlay1.boundingMapRect];
        BOOL contains1 = CGRectContainsRect(rect,rect1);
        if (contains1) {
            MapDetailedViewController *mapdVC=[[MapDetailedViewController alloc] initWithNibName:XIB_Version(@"MapDetailedViewController") bundle:nil];
            mapdVC.dic_mapPointBeanList=[arr_pop objectAtIndex:i];
            mapdVC.dic_mapRegionPhoneBeanList=[arr_phone objectAtIndex:i];
            [self.app.viewDeckController.navigationController pushViewController:mapdVC animated:YES];
            break;
        }
        i++;
        NSLog(@"%i",i);
    }
}
//地图标注 坐标
- (void)mapView:(BMKMapView *)mapView onClickedMapPoi:(BMKMapPoi*)mapPoi
{
    [text_select resignFirstResponder];
    if ([mapPoi.text isEqualToString:@"鞍山市高新区管委会"]) {
            NSLog(@"onClickedMapPoi-%@",mapPoi.text);
            NSString* showmeg = [NSString stringWithFormat:@"您点击了底图标注:%@,\r\n当前经度:%f,当前纬度:%f,\r\nZoomLevel=%d;RotateAngle=%d;OverlookAngle=%d",
                                 mapPoi.text,mapPoi.pt.longitude,mapPoi.pt.latitude, (int)_mapView.zoomLevel,_mapView.rotation,_mapView.overlooking];
            NSLog(@"%@",showmeg);

    }
    int i=0;
    for (id<BMKOverlay>  overlay in arr_rect) {
        
        BMKPolygonView* polygonView = [[BMKPolygonView alloc] initWithOverlay:overlay];
        CGRect rect=[polygonView rectForMapRect:overlay.boundingMapRect];
        
        CLLocationCoordinate2D coords[4]={0};
        coords[0].latitude = mapPoi.pt.latitude;
        coords[0].longitude = mapPoi.pt.longitude;
        coords[1].latitude = mapPoi.pt.latitude;
        coords[1].longitude = mapPoi.pt.longitude;
        coords[2].latitude = mapPoi.pt.latitude;
        coords[2].longitude = mapPoi.pt.longitude;
        coords[3].latitude = mapPoi.pt.latitude;
        coords[3].longitude = mapPoi.pt.longitude;
        BMKPolygon *polygon1 = [BMKPolygon polygonWithCoordinates:coords count:4];
        id<BMKOverlay> overlay1=polygon1;
        BMKPolygonView* polygonView1 = [[BMKPolygonView alloc] initWithOverlay:overlay1];
        CGRect rect1=[polygonView1 rectForMapRect:overlay1.boundingMapRect];
        BOOL contains1 = CGRectContainsRect(rect,rect1);
        if (contains1) {
            MapDetailedViewController *mapdVC=[[MapDetailedViewController alloc] initWithNibName:XIB_Version(@"MapDetailedViewController") bundle:nil];
            mapdVC.dic_mapPointBeanList=[arr_pop objectAtIndex:i];
            mapdVC.dic_mapRegionPhoneBeanList=[arr_phone objectAtIndex:i];
            [self.app.viewDeckController.navigationController pushViewController:mapdVC animated:YES];
            break;
        }
        i++;
    }

}
//地图标注annotationView 坐标
- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view
{
   
}
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
    
    
    
    NSString *str_title=view.annotation.title;
    NSLog(@"%@",str_title);
    BMKPoiInfo* poi=[dic_BMKPoiInfo objectForKey:str_title];
//    NSLog(@"poi.name=%@   poi.address=%@ poi.phone=%@",poi.name,poi.address,poi.phone);
    if (poi!=nil) {
        RoadMapViewController *roadmapVC=[[RoadMapViewController alloc] initWithNibName:@"RoadMapViewController" bundle:nil];
        roadmapVC.roadmapDelegate=self;
        roadmapVC.bmkpoiinfo=poi;
        roadmapVC.star=region.center;
        roadmapVC.end=poi.pt;
        [self.app.viewDeckController.navigationController pushViewController:roadmapVC animated:YES];
        roadmapVC=nil;
    }
    id<BMKAnnotation> annotation=view.annotation;
    int i=0;
    for (id<BMKAnnotation>  ann_item in arr_popAnnotation) {
        if ([ann_item isEqual:annotation]) {
            NSLog(@"%i",i);
            MapDetailedViewController *mapdVC=[[MapDetailedViewController alloc] initWithNibName:XIB_Version(@"MapDetailedViewController") bundle:nil];
            mapdVC.dic_mapPointBeanList=[arr_pop objectAtIndex:i];
            mapdVC.bool_ann=YES;
            [self.app.viewDeckController.navigationController pushViewController:mapdVC animated:YES];
            break;
        }
        i++;
    }
}

-(void)onGetWalkingRouteResult:(BMKSearch *)searcher result:(BMKPlanResult *)result errorCode:(int)error
{
   
	if (error == BMKErrorOk) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
        NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
        for (BMKPointAnnotation *Annotation in array) {
            for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
                if ([Annotation isEqual:Polygon1])
                {
                    [arr_Annotation removeObject:Polygon1];
                }
            }
        }
        [_mapView removeAnnotations:arr_Annotation];
        array = [NSMutableArray arrayWithArray:_mapView.overlays];
        NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
        for (BMKOverlayView *Overlay in array) {
            for (BMKPolygon *Polygon1 in arr_polygon) {
                if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
                {
                    [arr_Overlay removeObject:Polygon1];
                }
            }
            
        }
        [_mapView removeOverlays:arr_Overlay];
        
		BMKRoutePlan* plan = (BMKRoutePlan*)[result.plans objectAtIndex:0];
		RouteAnnotation* item = [[RouteAnnotation alloc]init];
		item.coordinate = result.startNode.pt;
		item.title = @"起点";
		item.type = 0;
		[_mapView addAnnotation:item];
//		[item release];
		
		int index = 0;
		int size = [plan.routes count];
		for (int i = 0; i < 1; i++) {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				index += len;
			}
		}
		
		BMKMapPoint* points = new BMKMapPoint[index];
		index = 0;
		
		for (int i = 0; i < 1; i++) {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
				memcpy(points + index, pointArray, len * sizeof(BMKMapPoint));
				index += len;
			}
			size = route.steps.count;
			for (int j = 0; j < size; j++) {
				BMKStep* step = [route.steps objectAtIndex:j];
				item = [[RouteAnnotation alloc]init];
				item.coordinate = step.pt;
				item.title = step.content;
				item.degree = step.degree * 30;
				item.type = 4;
				[_mapView addAnnotation:item];
//				[item release];
			}
			
		}
		
		item = [[RouteAnnotation alloc]init];
		item.coordinate = result.endNode.pt;
		item.type = 1;
		item.title = @"终点";
		[_mapView addAnnotation:item];
//		[item release];
		BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:points count:index];
		[_mapView addOverlay:polyLine];
		delete []points;
        [_mapView setCenterCoordinate:result.startNode.pt animated:YES];
	}
}
- (void)onGetDrivingRouteResult:(BMKSearch*)searcher result:(BMKPlanResult*)result errorCode:(int)error
{
    if (result != nil) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
        NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
        for (BMKPointAnnotation *Annotation in array) {
            for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
                if ([Annotation isEqual:Polygon1])
                {
                    [arr_Annotation removeObject:Polygon1];
                }
            }
        }
        [_mapView removeAnnotations:arr_Annotation];
        array = [NSMutableArray arrayWithArray:_mapView.overlays];
        NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
        for (BMKOverlayView *Overlay in array) {
            for (BMKPolygon *Polygon1 in arr_polygon) {
                if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
                {
                    [arr_Overlay removeObject:Polygon1];
                }
            }
            
        }
        [_mapView removeOverlays:arr_Overlay];
        
        // error 值的意义请参考BMKErrorCode
        if (error == BMKErrorOk) {
            BMKRoutePlan* plan = (BMKRoutePlan*)[result.plans objectAtIndex:0];
            
            // 添加起点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = result.startNode.pt;
            item.title = @"起点";
            item.type = 0;
            [_mapView addAnnotation:item];
//            [item release];
            
            
            // 下面开始计算路线，并添加驾车提示点
            int index = 0;
            int size = [plan.routes count];
            for (int i = 0; i < 1; i++) {
                BMKRoute* route = [plan.routes objectAtIndex:i];
                for (int j = 0; j < route.pointsCount; j++) {
                    int len = [route getPointsNum:j];
                    index += len;
                }
            }
            
            BMKMapPoint* points = new BMKMapPoint[index];
            index = 0;
            for (int i = 0; i < 1; i++) {
                BMKRoute* route = [plan.routes objectAtIndex:i];
                for (int j = 0; j < route.pointsCount; j++) {
                    int len = [route getPointsNum:j];
                    BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
                    memcpy(points + index, pointArray, len * sizeof(BMKMapPoint));
                    index += len;
                }
                size = route.steps.count;
                for (int j = 0; j < size; j++) {
                    // 添加驾车关键点
                    BMKStep* step = [route.steps objectAtIndex:j];
                    item = [[RouteAnnotation alloc]init];
                    item.coordinate = step.pt;
                    item.title = step.content;
                    item.degree = step.degree * 30;
                    item.type = 4;
                    [_mapView addAnnotation:item];
//                    [item release];
                }
                
            }
            
            // 添加终点
            item = [[RouteAnnotation alloc]init];
            item.coordinate = result.endNode.pt;
            item.type = 1;
            item.title = @"终点";
            [_mapView addAnnotation:item];
//            [item release];
            
            // 添加途经点
            if (result.wayNodes) {
                for (BMKPlanNode* tempNode in result.wayNodes) {
                    item = [[RouteAnnotation alloc]init];
                    item.coordinate = tempNode.pt;
                    item.type = 5;
                    item.title = tempNode.name;
                    [_mapView addAnnotation:item];
//                    [item release];
                }
            }
            
            // 根究计算的点，构造并添加路线覆盖物
            BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:points count:index];
            [_mapView addOverlay:polyLine];
            delete []points;
            
            [_mapView setCenterCoordinate:result.startNode.pt animated:YES];
        }
    }
}
- (void)onGetTransitRouteResult:(BMKSearch*)searcher result:(BMKPlanResult*)result errorCode:(int)error
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:_mapView.annotations];
    NSMutableArray *arr_Annotation=[[NSMutableArray alloc] initWithArray:array];
    for (BMKPointAnnotation *Annotation in array) {
        for (BMKPointAnnotation *Polygon1 in arr_popAnnotation) {
            if ([Annotation isEqual:Polygon1])
            {
                [arr_Annotation removeObject:Polygon1];
            }
        }
    }
    [_mapView removeAnnotations:arr_Annotation];
    array = [NSMutableArray arrayWithArray:_mapView.overlays];
    NSMutableArray *arr_Overlay=[[NSMutableArray alloc] initWithArray:array];
    for (BMKOverlayView *Overlay in array) {
        for (BMKPolygon *Polygon1 in arr_polygon) {
            if ([Overlay isEqual:(BMKOverlayView *)Polygon1])
            {
                [arr_Overlay removeObject:Polygon1];
            }
        }
        
    }
    [_mapView removeOverlays:arr_Overlay];
    if (error == BMKErrorOk) {
		BMKTransitRoutePlan* plan = (BMKTransitRoutePlan*)[result.plans objectAtIndex:0];
		RouteAnnotation* item = [[RouteAnnotation alloc]init];
		item.coordinate = plan.startPt;
		item.title = @"起点";
		item.type = 0;
		[_mapView addAnnotation:item]; // 添加起点标注
//		[item release];
        
		item = [[RouteAnnotation alloc]init];
		item.coordinate = plan.endPt;
		item.type = 1;
		item.title = @"终点";
		[_mapView addAnnotation:item]; // 终点标注
//		[item release];
		
        // 计算路线方案中的点数
		int size = [plan.lines count];
		int planPointCounts = 0;
		for (int i = 0; i < size; i++) {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				planPointCounts += len;
			}
			BMKLine* line = [plan.lines objectAtIndex:i];
			planPointCounts += line.pointsCount;
			if (i == size - 1) {
				i++;
				route = [plan.routes objectAtIndex:i];
				for (int j = 0; j < route.pointsCount; j++) {
					int len = [route getPointsNum:j];
					planPointCounts += len;
				}
				break;
			}
		}
		
        // 构造方案中点的数组，用户构建BMKPolyline
		BMKMapPoint* points = new BMKMapPoint[planPointCounts];
		planPointCounts = 0;
		
        // 查询队列中的元素，构建points数组，并添加公交标注
		for (int i = 0; i < size; i++) {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
				memcpy(points + planPointCounts, pointArray, len * sizeof(BMKMapPoint));
				planPointCounts += len;
			}
			BMKLine* line = [plan.lines objectAtIndex:i];
			memcpy(points + planPointCounts, line.points, line.pointsCount * sizeof(BMKMapPoint));
			planPointCounts += line.pointsCount;
			
			item = [[RouteAnnotation alloc]init];
			item.coordinate = line.getOnStopPoiInfo.pt;
			item.title = line.tip;
			if (line.type == 0) {
				item.type = 2;
			} else {
				item.type = 3;
			}
			
			[_mapView addAnnotation:item]; // 上车标注
//			[item release];
			route = [plan.routes objectAtIndex:i+1];
			item = [[RouteAnnotation alloc]init];
			item.coordinate = line.getOffStopPoiInfo.pt;
			item.title = route.tip;
			if (line.type == 0) {
				item.type = 2;
			} else {
				item.type = 3;
			}
			[_mapView addAnnotation:item]; // 下车标注
//			[item release];
			if (i == size - 1) {
				i++;
				route = [plan.routes objectAtIndex:i];
				for (int j = 0; j < route.pointsCount; j++) {
					int len = [route getPointsNum:j];
					BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
					memcpy(points + planPointCounts, pointArray, len * sizeof(BMKMapPoint));
					planPointCounts += len;
				}
				break;
			}
		}
        
        // 通过points构建BMKPolyline
		BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:points count:planPointCounts];
		[_mapView addOverlay:polyLine]; // 添加路线overlay
		delete []points;
        
        [_mapView setCenterCoordinate:result.startNode.pt animated:YES];
	}
}
//覆盖层画图
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
	if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    if ([overlay isKindOfClass:[BMKCircle class]])
    {
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
        circleView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.5];
        circleView.lineWidth = 5.0;
		return circleView;
    }
    if ([overlay isKindOfClass:[BMKPolygon class]])
    {
        BMKPolygonView* polygonView = [[BMKPolygonView alloc] initWithOverlay:overlay];
        polygonView.strokeColor = [[UIColor purpleColor] colorWithAlphaComponent:1];
        polygonView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.2];
        polygonView.lineWidth =2.0;
//        CGRect rect=[polygonView rectForMapRect:overlay.boundingMapRect];
//        NSLog(@"%f   %f   %f   %f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
        if (arr_rect.count>0) {
            BOOL b=YES;
            for (id<BMKOverlay> overlay1 in arr_rect) {
                if ([overlay isEqual:overlay1]) {
                    b=NO;
                }
            }
            if (b) {
                [arr_rect addObject:overlay];
            }
        }
        else
        {
            [arr_rect addObject:overlay];
        }
        
		return polygonView;
    }
	return nil;
}
- (void)mapView:(BMKMapView *)mapView didAddOverlayViews:(NSArray *)overlayViews
{
//    for(BMKOverlayView *OverlayViews in overlayViews)
//    {
//        (id<BMKOverlay> *)OverlayViews
//        CGRect rect=[OverlayViews rectForMapRect: ;
//        NSLog(@"%f   %f   %f   %f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
//    }
}


-(void)NearbyDelegate_select:(NSString *)tyeName page:(int)page
{
    text_select.text=tyeName;
    [self selectNearby:tyeName page:page];
}
//步行规划路线
-(void)WalkingRoutePlanning :(CLLocationCoordinate2D )star end:(CLLocationCoordinate2D)end
{
    BMKPlanNode *sart_map=[[BMKPlanNode alloc] init];
    sart_map.pt=star;
    BMKPlanNode *end_map=[[BMKPlanNode alloc] init];
    end_map.pt=end;
    [_search walkingSearch:@"鞍山" startNode:sart_map endCity:@"鞍山" endNode:end_map];
}
//公交规划路线
-(void)BusRoutePlanning :(CLLocationCoordinate2D )star end:(CLLocationCoordinate2D)end
{
    BMKPlanNode *sart_map=[[BMKPlanNode alloc] init];
    sart_map.pt=star;
    BMKPlanNode *end_map=[[BMKPlanNode alloc] init];
    end_map.pt=end;
    if ([_search transitSearch:@"鞍山" startNode:sart_map endNode:end_map]) {
        NSLog(@"成功");
    }
    else
    {
        NSLog(@"失败");
    }
}
//驾车规划路线
-(void)DriveRoutePlanning :(CLLocationCoordinate2D )star end:(CLLocationCoordinate2D)end
{
    BMKPlanNode *sart_map=[[BMKPlanNode alloc] init];
    sart_map.pt=star;
    BMKPlanNode *end_map=[[BMKPlanNode alloc] init];
    end_map.pt=end;
    [_search drivingSearch:@"鞍山" startNode:sart_map endCity:@"鞍山" endNode:end_map];
}
-(void)addOverlayView
{
    NSString *url=@"phone!getMapList.action";
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *ary_success=[dic_result objectForKey:@"context"];
        for(NSDictionary *dic_item in ary_success)
        {
            arr_pop=[dic_item objectForKey:@"mapPointBeanList"];
            for(NSDictionary *dic_item in arr_pop)
            {
                
                BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
                CLLocationCoordinate2D coordinate;
                coordinate.longitude= [[dic_item objectForKey:@"pointX"] floatValue];
                coordinate.latitude=[[dic_item objectForKey:@"pointY"] floatValue];
                item.coordinate = coordinate;
                item.title = [dic_item objectForKey:@"title"];
                [arr_popAnnotation addObject:item];
                [_mapView addAnnotation:item];
                
            }
            arr_phone=[dic_item objectForKey:@"mapRegionPhoneBeanList"];
            for(NSDictionary *dic_context in arr_phone)
            {
                NSString *s=[dic_context objectForKey:@"mapRegionInfo"];
                NSLog(@"%@",s);
                NSArray *arr_longitude=[dic_context objectForKey:@"pointXList"];
                NSArray *arr_latitude=[dic_context objectForKey:@"pointYList"];
                int i=arr_latitude.count;
                CLLocationCoordinate2D coords[i] ;
                for (int j=0; j<i; j++)
                {
                    coords[j].latitude = [[arr_latitude objectAtIndex:j] floatValue];
                    coords[j].longitude = [[arr_longitude objectAtIndex:j] floatValue];
                }
                BMKPolygon *polygon1 = [BMKPolygon polygonWithCoordinates:coords count:i];
                [_mapView addOverlay:polygon1];
                [arr_polygon addObject:polygon1];
            }
        }
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        if (isarler) {
            NSString *message=[self ErrorMessageHandling:error];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            alert=nil;
            isarler=NO;
        }

        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    

    
}
//-(BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay
//{
//becomefirstresponder
//}
@end
